import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Collapse} from 'antd';
import {FORM_OPTIONS} from '../constants';
import {conventEnumValueToString, formatAmount} from '../utils';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {PERMISSION, hasPermissions} from './constants';
import {currency} from '../Enum';
import routes from './routes';
import {getDetail} from './api';
import styles from './style.css';
import DetailTable from './DetailTable';
import FormItem from 'antd/lib/form/FormItem';
import TextInput from 'Shared/components/TextInput';
import FileUpload from './FileUpload';
import {injectIntl, formatMessage} from './intl';
const Panel = Collapse.Panel;
const {Description} = DescriptionList;

export class UploadPanel extends React.PureComponent {
    state = {
        loading: false,
        data: {
            goodwillSettlementDetails: []
        }
    };

    componentDidMount() {
        this.getDetailInfo();
    }

    getDetailInfo = () => {
        this.setState({loading: true});
        getDetail(this.props.id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onSubmit = () => {
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    render() {
        const operations = [];
        const {data = {}} = this.state;
        const {permissions, onCancel} = this.props;
        const submitable = hasPermissions(PERMISSION.confirm, permissions);
        const packingPanel = data.goodwillSettlementDetails.map(item => {
            const header = (
                <Row>
                    <Col span={4}>
                        {`${formatMessage({
                            id: 'detailPage.info.goodWillCode',
                            defaultMessage: 'GoodWill编号'
                        })}: ${item.goodWillCode}`}
                    </Col>
                    <Col span={4}>
                        {`${formatMessage({
                            id: 'detailPage.info.laborFee',
                            defaultMessage: '工时费'
                        })}: ${item.laborFee}`}
                    </Col>
                    <Col span={4}>
                        {`${formatMessage({
                            id: 'detailPage.info.materialFee',
                            defaultMessage: '材料费'
                        })}: ${item.materialFee}`}
                    </Col>
                    <Col span={4}>
                        {`${formatMessage({
                            id: 'detailPage.info.totalFee',
                            defaultMessage: '费用合计'
                        })}: ${item.totalFee}`}
                    </Col>
                </Row>
            );
            const dataSource = item.goodWillDetails || [];
            return (
                <Panel key={item.id} header={header}>
                    <DetailTable data={dataSource} />
                </Panel>
            );
        });
        if(hasPermissions(permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        return (
            <div className={styles.detail}>
                <Card loading={this.state.loading}>
                    <DescriptionList size="large" title={<Row><Col span={12}>{
                        formatMessage({
                            id: 'detailPage.card.tradeMethodmessage',
                            defaultMessage: '基本信息'
                        })
                    }</Col>
                    <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                    </Row>}>
                        <Description term={formatMessage({
                            id: 'detailPage.data.code',
                            defaultMessage: '编号',
                        })}>{data.code}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.brand',
                            defaultMessage: '品牌'
                        })}>{`(${data.brandCode})${data.brandName}`}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.dealer',
                            defaultMessage: '总代',
                        })}>{`(${data.dealerCode})${data.dealerName}`}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.currency',
                            defaultMessage: '币种'
                        })}>{conventEnumValueToString(currency, data.currency)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.country',
                            defaultMessage: '国家'
                        })}>{data.country}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.laborFee',
                            defaultMessage: '工时费合计',
                        })}>{formatAmount(data.laborFee)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.materialFee',
                            defaultMessage: '材料费'
                        })}>{formatAmount(data.materialFee)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.totalFee',
                            defaultMessage: '费用合计'
                        })}>{formatAmount(data.totalFee)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.comment',
                            defaultMessage: '业务内容'
                        })}>{data.comment}</Description>
                        <Description term={formatMessage({
                            id: 'detailPage.data.remark',
                            defaultMessage: '备注'
                        })}>{data.remark}</Description>
                    </DescriptionList>
                </Card>
                <Card
                    title={formatMessage({
                        id: 'detailPage.details.title',
                        defaultMessage: 'GoodWill结算清单'
                    })}
                    bordered={false}>
                    <Collapse>
                        {packingPanel}
                    </Collapse>
                </Card>
                <Card title={formatMessage({
                    id: 'newPanel.title.files',
                    defaultMessage: '附件清单'
                })}>
                    <Row>
                        <Col {...FORM_OPTIONS.col}>
                            <FileUpload onChange={this.onChangeUpload}
                                onRemove={this.removeFilePath}
                                fileList={data.attachments || []}/>
                        </Col>
                    </Row>
                </Card>
                <Card {...FORM_OPTIONS.col} title={formatMessage({
                    id: 'confirmPanel.card.comment',
                    defaultMessage: '意见'
                })}>
                    <Row>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={formatMessage({
                                    id: 'confirmPanel.form.uplpadComment',
                                    defaultMessage: '上传意见'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    type="textarea"
                                    name="uplpadComment"
                                    value={data.uplpadComment}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={formatMessage({
                                    id: 'confirmPanel.form.approveComment',
                                    defaultMessage: '确认意见'
                                })}
                                {...FORM_OPTIONS.item} >
                                {data.approveComment}
                            </FormItem>
                        </Col>
                    </Row>
                </Card>
                <Card type="inner">
                    <Row>
                        <Col disabled={!submitable} className="col-align-right">
                            <Button key="submit" loading={this.state.loading}
                                onClick={this.onSubmit} type="primary">{formatMessage({
                                    id: 'confirmPanel.btn.submit',
                                    defaultMessage: '保存'
                                })}</Button>
                        </Col>
                    </Row>
                </Card>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={onCancel}>{formatMessage({
                            id: 'detailPage.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

UploadPanel.propTypes = {
    id: PropTypes.string.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {onUpload, tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    id: props.id,
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onUpload(data)).then(result => {
        if(result.success) {
            dispatch(tableSearch());
            props.history.push(routes.query.url());
        }
    }),
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UploadPanel));
